#pragma once

#include <mutex>
#include <condition_variable>
#include "EventLoop.hpp"

class LoopThread
{
private:
    EventLoop *_loop;
    std::mutex _mutex;
    std::condition_variable _cond;
    std::thread _thread;

private:
    void ThreadEntry()
    {
        EventLoop loop;
        {
            std::unique_lock<std::mutex> _lock(_mutex);
            _loop = &loop;
            // 唤醒所以线程
            _cond.notify_all();
        }
        // 启动epoll事件监控
        _loop->StartReactor();
    }

public:
    LoopThread()
        : _loop(nullptr), _thread(std::thread(&LoopThread::ThreadEntry, this)) {}
    ~LoopThread() = default;

    //获取loop对象
    EventLoop* GetLoop()
    {
        EventLoop* loop = nullptr;
        {
            std::unique_lock<std::mutex> lock(_mutex);
            _cond.wait(lock, [&] { return _loop != nullptr; } );
            loop = _loop;
        }
        return loop;
    }
};